const db = require("../models");
const DAO = require("../dao/DAO");

const UserAddress = db.userAddress;

// 创建用户地址
exports.createUserAddress = (req, res) => {
  const { userId, userAddress } = req.body;
  // 请求验证
  if (!userId)
    return res.sendResult({ data: "", code: 500, message: "用户ID不能为空！" });

  if (!userAddress)
    return res.sendResult({
      data: "",
      code: 500,
      message: "地址不能为空！",
    });

  const userAddressInfo = {
    uid: userId,
    userAddress,
  };

  UserAddress.findOne({ where: userAddressInfo }).then((address) => {
    if (address === userAddress) {
      return res.sendResultAto(null, 505, "该地址已存在！");
    }
    DAO.create(UserAddress, userAddressInfo, (data) => {
      res.sendResult(data);
    });
  });
};

// 修改用户地址
exports.updateUserAddress = (req, res) => {
  const pm = req.body;
  // 请求验证
  if (!pm.id)
    return res.sendResult({ data: "", code: 500, message: "ID不能为空！" });

  DAO.update(UserAddress, pm, { id: pm.id }, (data) => {
    res.sendResult(data);
  });
};

// 删除用户地址
exports.deleteUserAddress = (req, res) => {
  console.log(req);
  const pm = req.query;
  // 请求验证
  if (!pm.id)
    return res.sendResult({ data: "", code: 500, message: "ID不能为空！" });
  DAO.delete(UserAddress, { id: pm.id }, (data) => {
    res.sendResult(data);
  });
};

// 查询用户地址
exports.findUserAllAddress = (req, res) => {
  const { userId } = req.query;
  console.log(req.query);
  DAO.list(
    UserAddress,
    {
      params: {
        uid: userId,
      },
    },
    (list) => {
      res.sendResult(list);
    }
  );
};
